package web

import (
	"embed"
	"io/fs"
	"net/http"
	"strings"
)

//go:embed dist/*
var embedFS embed.FS

// GetFileSystem 返回嵌入的文件系统
func GetFileSystem() http.FileSystem {
	fsys, err := fs.Sub(embedFS, "dist")
	if err != nil {
		panic(err)
	}
	return http.FS(fsys)
}

// SPAHandler 处理SPA应用的路由
func SPAHandler(staticFS http.FileSystem) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path

		// API路由直接跳过
		if strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/swagger/") || strings.HasPrefix(path, "/health") {
			return
		}

		// 尝试获取文件
		_, err := staticFS.Open(path)
		if err != nil {
			// 文件不存在，返回index.html用于SPA路由
			index, err := staticFS.Open("/index.html")
			if err != nil {
				w.WriteHeader(http.StatusNotFound)
				return
			}
			defer index.Close()

			stat, _ := index.Stat()
			http.ServeContent(w, r, "index.html", stat.ModTime(), index)
			return
		}

		// 文件存在，正常服务
		http.FileServer(staticFS).ServeHTTP(w, r)
	}
}